package com.blb.mvc.controller;

import com.blb.mvc.entity.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Controller
public class FileController {

    @RequestMapping("/toUpload")
    public String toUpload(){
        return "file-upload";
    }

    /**
     * 上传书籍信息
     * file表单的name不能和实体类Book中的属性相同
     * 属性=值&属性=值
     */
    @PostMapping("/upload")
    public String addBook(Book book, MultipartFile[] pics) throws IOException {
        //获得upload目录的绝对路径
        String path = "D:\\upload\\";
        System.out.println(path);
        //没有该目录就新建一个
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        String picture = "";
        for(MultipartFile pic : pics){
            //获得原始文件名，截取后缀名，用uuid生成新文件名
            String filename = pic.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));
            filename = UUID.randomUUID().toString().replace("-","") + suffix;
            //将原来的文件保存到新文件中
            pic.transferTo(new File(path + filename));
            picture += filename + ",";
        }
        book.setPicture(picture);
        System.out.println(book);
        return "file-upload"; //model+view 逻辑视图
    }

    @RequestMapping("/download")
    public void download(String file,  HttpServletResponse response) throws IOException {
        //下载文件的路径
        String path = "D:\\upload\\";
        File downFile = new File(path + file);
        if(downFile.exists()){
            //设置浏览器下载内容类型，响应头
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition","attachment;filename="+file);
            //通过流发送文件
            Files.copy(downFile.toPath(),response.getOutputStream());
        }
    }

    //将数据直接响应给前端，不包含视图信息
    @ResponseBody
    @RequestMapping("/addBook")  //add delete update select save insert get find remove
    //不加RequestBody就是表单格式，加了就是JSON格式
    public List<Book> addBook(@RequestBody Book book){
        System.out.println(book);
        List<Book> books = Arrays.asList(new Book("三国演义","罗贯中",44.4,"xx.jpg"),
                new Book("水浒传","施耐庵",44.4,"xx.jpg"),
                new Book("西游记","吴承恩",44.4,"xx.jpg"));
        return books;
    }
}
